package com.tenebrous.jestic.controller;

import com.tenebrous.jestic.entity.framwork.meber.author.AuthRole;
import com.tenebrous.jestic.entity.framwork.meber.organ.OrgUser;
import com.tenebrous.jestic.service.framwork.meber.author.AuthRoleService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class SupperController {

    @Autowired
    private AuthRoleService roleService;

    protected HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        return ((ServletRequestAttributes) requestAttributes).getRequest();
    }

    protected HttpSession getSession() {
        return this.getRequest().getSession();
    }

    protected ServletContext getApplication() {
        return this.getSession().getServletContext();
    }

    protected String getSessionString(String key) {
        Object obj = this.getSession().getAttribute(key);
        return obj != null ? obj.toString() : null;
    }

    protected Object getSessionObject(String key) {
        return this.getSession().getAttribute(key);
    }

    protected void setSession(String key, Object value) {
        this.getSession().setAttribute(key, value);
    }

    protected void setRequest(String key, Object value) {
        this.getRequest().setAttribute(key, value);
    }

    protected String getParameter(String key) {
        return this.getRequest().getParameter(key);
    }

    /**
     * 默认值1
     *
     * @return
     */
    protected int getPageIndex() {
        String v = this.getParameter("page");
        if (StringUtils.isNotBlank(v)) {
            return Integer.parseInt(v);
        }
        return 1;
    }

    /**
     * 默认值10
     *
     * @return
     */
    protected int getPageSize() {
        String v = this.getParameter("rows");
        if (StringUtils.isNotBlank(v)) {
            return Integer.parseInt(v);
        }
        return 10;
    }

    protected String getRealPath(String path) {
        return this.getSession().getServletContext()
                .getRealPath(path);
    }

    protected String getToken() {
        String token = this.getRequest().getHeader("token");
        if (StringUtils.isBlank(token)) {
            token = this.getRequest().getParameter("token");
        }
        return token;
    }

    protected String getRoleid() {
        String roleid = this.getRequest().getHeader("roleid");
        if (StringUtils.isBlank(roleid)) {
            roleid = this.getRequest().getParameter("roleid");
        }
        return roleid;
    }

    /**
     * 获取当前登录用户信息
     *
     * @return
     */
    protected OrgUser getCurrentUser() {
        String sessionid = this.getSession().getId();
        Object object = this.getSessionObject(sessionid);
        if (object != null) {
            return (OrgUser) object;
        }
        return null;
    }

    protected AuthRole getCurrentRole() {
        String rid = this.getRoleid();
        if (StringUtils.isNotBlank(rid)) {
            return this.roleService.selectByPrimaryKey(rid);
        }
        return null;
    }

    /**
     * 获取用户访问IP地址
     *
     * @return
     */
    public String getIPAddress() {
        String ip = null;
        HttpServletRequest request = this.getRequest();
        //X-Forwarded-For：Squid 服务代理
        String ipAddresses = request.getHeader("X-Forwarded-For");

        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //Proxy-Client-IP：apache 服务代理
            ipAddresses = request.getHeader("Proxy-Client-IP");
        }

        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //WL-Proxy-Client-IP：weblogic 服务代理
            ipAddresses = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //HTTP_CLIENT_IP：有些代理服务器
            ipAddresses = request.getHeader("HTTP_CLIENT_IP");
        }

        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //X-Real-IP：nginx服务代理
            ipAddresses = request.getHeader("X-Real-IP");
        }

        //有些网络通过多层代理，那么获取到的ip就会有多个，一般都是通过逗号（,）分割开来，并且第一个ip为客户端的真实IP
        if (ipAddresses != null && ipAddresses.length() != 0) {
            ip = ipAddresses.split(",")[0];
        }

        //还是不能获取到，最后再通过request.getRemoteAddr();获取
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
